package com.das.mechanic_base.utils;

import android.content.Context;
import android.content.MutableContextWrapper;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;

import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.bean.common.LocaleBean;
import com.das.mechanic_base.widget.X3NewWebView;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


//import android.webkit.CookieSyncManager;

public class WebViewPool {

    public static long startTime ;

    private static final String APP_CACAHE_DIRNAME = "webCache";

    private static List<X3NewWebView> available = new ArrayList<>();
    private static final Stack<WebView> mCachedWebViewStack = new Stack<>();
    private static List<X3NewWebView> inUse = new ArrayList<>();

    private static final byte[] lock = new byte[]{};
    private static int maxSize = 2;
    private static volatile WebViewPool instance = null;

    private static Context mContext;

    public static WebViewPool getInstance() {
        if (instance == null) {
            synchronized (WebViewPool.class) {
                if (instance == null) {
                    instance = new WebViewPool();
                }
            }
        }
        return instance;
    }

    /**
     * Webview 初始化
     * 最好放在application oncreate里
     */
    public static void init(Context context) {
        for (int i = available.size(); i < maxSize; i++) {
            try {
                long start = System.currentTimeMillis();

                X3NewWebView webView = new X3NewWebView(new MutableContextWrapper(context));
                initWebSeting(context, webView);
                long end = System.currentTimeMillis();
                Log.e("init-X3NewWebView",(end - start) + "");
                available.add(webView);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取webview
     */
    public X3NewWebView getWebView(Context context) {
        synchronized (lock) {
            X3NewWebView webView;
            if (available.size() > 0) {
                Log.e("getWebView---","available.size() > 0");
                webView = available.get(0);
                available.remove(0);
//                inUse.add(webView);
                if (webView == null){
                    Log.e("getWebView---","webView == null");
                } else {
                    Log.e("getWebView---","webView != null");
                }
            } else {
                webView = new X3NewWebView(new MutableContextWrapper(context));
                initWebSeting(context, webView);
//                inUse.add(webView);
                Log.e("getWebView---","new webView");
            }
            return webView;
        }
    }

    /**
     * 回收webview ,不解绑
     *
     * @param webView 需要被回收的webview
     */
    public void removeWebView(X3NewWebView webView) {
        webView.loadUrl("");
        webView.stopLoading();
        webView.setNewWebChromeClient(null);
        webView.setNewWebViewClient(null);
        webView.clearCache(true);
        webView.clearHistory();
        synchronized (lock) {
            inUse.remove(webView);
            if (available.size() < maxSize) {
                available.add(webView);
            } else {
                webView = null;
            }
        }
    }

    /**
     * 回收webview ,解绑
     *
     * @param webView 需要被回收的webview
     */
    public void removeWebView(ViewGroup viewGroup, X3NewWebView webView) {
        viewGroup.removeView(webView);
        webView.loadUrl("");
        webView.stopLoading();
        webView.setNewWebChromeClient(null);
        webView.setNewWebViewClient(null);
        webView.clearCache(true);
        webView.clearHistory();
        synchronized (lock) {
            inUse.remove(webView);
            if (available.size() < maxSize) {
                available.add(webView);
            } else {
                webView = null;
            }
        }
    }

    /**
     * 设置webview池个数
     *
     * @param size webview池个数
     */
    public void setMaxPoolSize(int size) {
        synchronized (lock) {
            maxSize = size;
        }
    }

    private static void initWebSeting(Context context, WebView webView) {
        mContext = context;
        webView.setWebChromeClient(new MyBrowserChromeClient(webView));
        webView.setWebViewClient(new MyBrowserViewClient());
        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(false); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(false); // 缩放至屏幕的大小
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        //启用地理定位
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setBlockNetworkLoads(false);
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 解决 Android 5.0 上 WebView 默认不允许加载 Http 与 Https 混合内容
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        // 不显示滚动条
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);
    }

    public void synchronousWebCookies(Context context, String url) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookies(null);// 移除
        cookieManager.removeAllCookie();
        StringBuilder sbCookieToken = new StringBuilder();
        sbCookieToken.append(String.format("Authorization=%s", SpHelper.getData("token", "")));
        String cookieValueToken = sbCookieToken.toString();

        LocaleBean appLocale = LanguageUtiles.getAppLocale(LanguageUtiles.appContext);
        String language = (String) SpHelper.getData("language","en-GB");

        StringBuilder local = new StringBuilder();
        local.append(String.format("lang=%s", language));
        String localStr = local.toString();

        String km = (String) SpHelper.getData(X3Constent.MILEAGEUNIT, "km");
        StringBuilder miles = new StringBuilder();
        miles.append(String.format("mileageUnit=%s", km));
        String mileStr = miles.toString();

        String gbp = (String) SpHelper.getData(X3Constent.MONEYUNIT, "CNY");
        StringBuilder moneyUnit = new StringBuilder();
        moneyUnit.append(String.format("currencyCode=%s", gbp));
        String unitStr = moneyUnit.toString();

        String moneyCode = (String) SpHelper.getData(X3Constent.MONEYCODE, "£");
        StringBuilder code = new StringBuilder();
        code.append(String.format("currencyValue=%s", moneyCode));
        String codeStr = code.toString();

        boolean isSdk = (boolean) SpHelper.getData(X3Constent.IS_OPEN_SDK, false);
        if (isSdk) {
            StringBuilder sdk = new StringBuilder();
            sdk.append(String.format("projectSource=%s", "SDK"));
            cookieManager.setCookie(url, sdk.toString());
        }

        cookieManager.setCookie(url, cookieValueToken);
        cookieManager.setCookie(url, localStr);
        cookieManager.setCookie(url, mileStr);
        cookieManager.setCookie(url, unitStr);
        cookieManager.setCookie(url, codeStr);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.getInstance().sync();
        } else {
            CookieManager.getInstance().flush();
        }
    }

    public static class MyBrowserViewClient extends X3NewWebView.NewWebViewClient {

        public WebViewSettingListener webViewSettingListener;

        /**
         * 网页加载错误时回调，这个方法会在 onPageFinished 之前调用
         */
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // 这里为什么要用延迟呢？因为加载出错之后会先调用 onReceivedError 再调用 onPageFinished
//            post(() -> showError(v -> reload()));
        }

        /**
         * 开始加载网页
         */
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            try {
                if (webViewSettingListener != null){
                    webViewSettingListener.onPageStarted();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        /**
         * 完成加载网页
         */
        @Override
        public void onPageFinished(WebView webView, String url) {
            //页面finish后再发起图片加载
            if(!webView.getSettings().getLoadsImagesAutomatically()) {
                webView.getSettings().setLoadsImagesAutomatically(true);
            }
        }

        /**
         * 该方法在加载页面资源时会回调，每一个资源（比如图片）的加载都会调用一次。
         * @param view
         * @param url
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Nullable
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            return super.shouldInterceptRequest(view, request);
        }

        @Nullable
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//            if (StringUtils.isEmpty(url)) {
//                return super.shouldInterceptRequest(view, url);
//            }
//            try {
//                url = url.replace(Constent.getH5BaseUrl(), "").replace("https://h5test.autox3.com/mechanic/", "").
//                        replace("http://192.168.1.91:801/mechanic/", "").replace("https://h5cnpre.autox3.com/mechanic/", "");
//                if (url.contains(".html")) {
//                    return super.shouldInterceptRequest(view, url);
//                }
//                url = url.replaceAll("\\?.*","");
//                url = url.substring(url.lastIndexOf("/"));
//
//                Log.e("QQQQ", "加载本地jquery.js : " + url);
//                if (url.endsWith(".css")) {
//                    return new WebResourceResponse("text/css", "utf-8", mContext.getAssets().open("www" + url));
//                }else if (url.endsWith(".js")) {
//                    return new WebResourceResponse("application/x-javascript", "utf-8", mContext.getAssets().open("www" + url));
//                }else if (url.endsWith(".json")) {
//                    return new WebResourceResponse("application/json", "utf-8", mContext.getAssets().open("www" + url));
//                }
//                return new WebResourceResponse("image/*", "utf-8", mContext.getAssets().open("www" + url));
//            } catch (IOException e) {
//                e.printStackTrace();
////                Log.e("QQQQ", "加载本地js错误："+e.toString());
//            }
            //需处理特殊情况
            return super.shouldInterceptRequest(view, url);
        }
    }

    public static class MyBrowserChromeClient extends X3NewWebView.BrowserChromeClient {

        public WebViewSettingListener webViewSettingListener;

        public MyBrowserChromeClient(WebView view) {
            super(view);
        }

        /**
         * 收到网页标题
         */
        @Override
        public void onReceivedTitle(WebView view, String title) {

        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {

        }

        /**
         * 收到加载进度变化
         */
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            try {
                 if (webViewSettingListener != null){
                     webViewSettingListener.onProgressChange(newProgress);
                 }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        /**
         * 网页弹出警告框
         */
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }

        /**
         * 网页弹出确定取消框
         */
        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    }


    public WebViewSettingListener webViewSettingListener;

    public interface WebViewSettingListener{
        void onProgressChange(int progress);
        void onPageStarted();
    }
}
